//
//  ECMineFavViewController.m
//  Edu_iOS2018
//
//  Created by apple on 2018/1/6.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#define Bottom_Height 145.f

#import "ECMineFavViewController.h"
#import "ECMineFavCell.h"
#import "ECMineFavMode.h"

#import "ECTipCustomView.h"

#import "ECUIVC_CourseDetail.h"
#import "CourseModel.h"
#import "UIImage+RenderedImage.h"

@interface ECMineFavViewController ()<UITableViewDelegate,UITableViewDataSource,ECTipCustomViewDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    /// 右上角编辑按钮
    UIButton *button;
    /// 底部view上确认取消收藏按钮
    ECUButton *makeSureBtn;
    /// 底部view上全选按钮
    ECUButton *selectAllBtn;
    ///批量删除存放id的数组
    NSMutableArray *idsArray;
    ///区分是否是批量删除的标志 999表示批量删除
    NSInteger isMoreDel;
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
///存放选中数据
@property (nonatomic, strong) NSMutableArray *selectorPatnArray;
///总个数
@property (nonatomic, assign) int allPageNum;
///提示对话框View
@property (nonatomic, strong) ECTipCustomView * tipCustomView;
///编辑状态下底部view
@property (nonatomic, strong) UIView *bottomView;

@end

@implementation ECMineFavViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar lt_setBackgroundColor:[UIColor whiteColor]];
    self.navigationController.navigationBar.shadowImage = [UIImage imageWithColor: [[UIColor darkGrayColor] colorWithAlphaComponent:1] renderSize:CGSizeMake(kScreenWidth, 0.20)];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"课程收藏";
    
    self.tipCustomView = [[ECTipCustomView alloc]init];
    self.tipCustomView.delegate = self;
    
    [self.view addSubview:self.tableView];
    
    [self getDataWithURL];
}

//右上角编辑按钮
-(void)setNavigationItemButtonConfig{
    button = [ECUButton buttonWithType:0];
    [button setTitle:@"编辑" forState:0];
    [button setTitleColor:[UIColor blackColor] forState:0];
    button.frame = CGRectMake(0, 0, 50, 20);
    [button addTarget:self action:@selector(selectMore:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
}

/*  加载数据  */
-(void)getDataWithURL{
    DLog(@"%@",[[UserInfoManager shareUser] token]);
    [HWHttpTool requestWithMethod:@"GET"
                              url:URL_GET_Me_Courses
                           params:@{@"start":@(self.dataArray.count),
                                    @"relation":@"favorited",
                                    @"limit":@"10"
                                    }
                          headers:@{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {
                              DLog(@"%@",json);
                              [self.tableView.mj_footer endRefreshing];//结束刷新
                              if ([json[@"code"] intValue] == 200) {
                                  self.allPageNum = [json[@"data"][@"total"] intValue];//总个数
                                  if (self.allPageNum > 0) {//只有数组数量大于0的情况下,编辑按钮才会加载
                                      [self setNavigationItemButtonConfig];
                                  }
                                  NSArray *array = json[@"data"][@"resources"];
                                  
                                  //当刷新成功后,改变状态
                                  if (self.selectorPatnArray.count > 0) {
                                      [selectAllBtn setTitle:@"全选" forState:0];
                                      [selectAllBtn setImage:[UIImage imageNamed:@"Mine_circleImage_normal"] forState:0];
                                      selectAllBtn.selected = NO;
                                      [makeSureBtn setTitle:@"取消收藏" forState:0];
                                      [self.selectorPatnArray removeAllObjects];
                                  }
                                  
                                  [self.dataArray addObjectsFromArray: [ECMineFavMode mj_objectArrayWithKeyValuesArray:array]];
                                  
                                  if (self.dataArray.count >= self.allPageNum) {
                                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                                      self.tableView.mj_footer.hidden = YES;
                                  } else {
                                      self.tableView.mj_footer.hidden = NO;
                                  }
                                  [self.tableView reloadData];
                              }else{
                                  [MBProgressHUD showTipMessageInWindow:json[@"message"]];
                              }
                          }
                          failure:^(NSError *error) {
                              [self.tableView.mj_footer endRefreshing];
                              [MBProgressHUD showErrorMessage:[ECData_Json requestErrorTipWith:error]];
                          }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellIdentifier = [NSString stringWithFormat:@"cell%ld",indexPath.row];//采用原来固定的标识会出现复用错误:编辑状态下,圆圈的复用崔安问题
    ECMineFavCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[ECMineFavCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    }
    [cell setContentMode:self.dataArray[indexPath.row]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return kProportion_Height(258);
}

//进入编辑模式
- (void)selectMore:(UIBarButtonItem *)action{
    // 编辑模式下多选
    self.tableView.allowsMultipleSelectionDuringEditing = true;
    
    if ([button.titleLabel.text isEqualToString:@"编辑"]) {
        
        [button setTitle:@"取消" forState:0];
        //进入编辑状态
        [self.tableView setEditing:YES animated:YES];
        
        ///更新tableview位置
        [self updateTableviewFram];
        
    }else{
        [button setTitle:@"编辑" forState:0];
        //对选中内容进行操作
        DLog(@"选中个数是 : %lu   内容为 : %@",(unsigned long)self.selectorPatnArray.count,self.selectorPatnArray);
        //取消编辑状态
        [self.tableView setEditing:NO animated:YES];
        
        //退出编辑状态,清空数组
        [self.selectorPatnArray removeAllObjects];
        
        //退出编辑状态 tableview更新约束 去除页面下部view;
        [self resetTableviewFram];

    }
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //正常状态下点击cell
    if (!tableView.editing) {
        CourseModel *courseModel = [[CourseModel alloc]init];
        ECMineFavMode *model = self.dataArray[indexPath.row];
        courseModel.modelId = model.ID;
        ECUIVC_CourseDetail *vc = [[ECUIVC_CourseDetail alloc]init];
        vc.object = courseModel;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        //选中数据
        [self.selectorPatnArray addObject:self.dataArray[indexPath.row]];
        ///实时改变取消收藏按钮的值
        [makeSureBtn setTitle:[NSString stringWithFormat:@"取消收藏(%ld)",self.selectorPatnArray.count] forState:0];
        
        ///改变编辑 选中状态下左边的小圆圈image
        ECMineFavCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSArray *subviews = cell.subviews;
        for (id subCell in subviews) {
            if ([subCell isKindOfClass:[UIControl class]]) {
                for (UIImageView *circleImage in [subCell subviews]) {
                    circleImage.image = [UIImage imageNamed:@"Mine_circleImage_select"];
                }
            }
        }
        
        if (self.selectorPatnArray.count < self.dataArray.count ) {
            //改变全选按钮的状态
            selectAllBtn.selected = NO;
            [selectAllBtn setTitle:@"全选" forState:0];
            [selectAllBtn setImage:[UIImage imageNamed:@"Mine_circleImage_normal"] forState:0];
        }else{
            //改变全选按钮的状态
            selectAllBtn.selected = YES;
            [selectAllBtn setTitle:@"取消全选" forState:0];
            [selectAllBtn setImage:[UIImage imageNamed:@"Mine_circleImage_select"] forState:0];
        }
    }
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    //正常状态下的取消选中cell
    if (!tableView.editing) {
        
    }else{
        //从选中中取消
        if (self.selectorPatnArray.count > 0) {
            [self.selectorPatnArray removeObject:self.dataArray[indexPath.row]];
             [makeSureBtn setTitle:[NSString stringWithFormat:@"取消收藏(%ld)",self.selectorPatnArray.count] forState:0];
        }
        
        ///改变编辑 未选中状态下左边的小圆圈image
        ECMineFavCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        NSArray *subviews = cell.subviews;
        for (id subCell in subviews) {
            if ([subCell isKindOfClass:[UIControl class]]) {
                for (UIImageView *circleImage in [subCell subviews]) {
                    circleImage.image = [UIImage imageNamed:@"Mine_circleImage_normal"];
                }
            }
        }
        
        if (self.selectorPatnArray.count < self.dataArray.count ) {
            //改变全选按钮的状态
            selectAllBtn.selected = NO;
            [selectAllBtn setTitle:@"全选" forState:0];
            [selectAllBtn setImage:[UIImage imageNamed:@"Mine_circleImage_normal"] forState:0];
        }else{
            
        }
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//滑动删除按钮
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    DLog(@"取消收藏");
    
    [self.tipCustomView showTipviewWithTpe:tipTypeOfCancelFavorite andIndexPath:indexPath.row];
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"取消收藏";
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"Mine_emptyImage_MineFav"];
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state;{
    NSString *text = @"你还没有收藏任何课程";
    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:16.0f],NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#b3b3b3"]};
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

-(void)emptyDataSet:(UIScrollView *)scrollView didTapButton:(UIButton *)button{
}

/**
 底部view
 */
-(UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, kScreenHeight - kProportion_Height(Bottom_Height)-kSafeAreaBottomHeight, kScreenWidth, kProportion_Height(Bottom_Height))];
        _bottomView.backgroundColor = [UIColor whiteColor];
        
        //全选按钮
        selectAllBtn = [ECUButton buttonWithType:UIButtonTypeCustom];
        [_bottomView addSubview:selectAllBtn];
        [selectAllBtn setTitle:@"全选" forState:0];
        [selectAllBtn setImage:[UIImage imageNamed:@"Mine_circleImage_normal"] forState:0];
        [selectAllBtn setTitleColor:[UIColor colorWithHexString:@"#666666"] forState:0];
        [selectAllBtn addTarget:self action:@selector(selectAllBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [selectAllBtn setTitleEdgeInsets:UIEdgeInsetsMake(0,0,0,0)];
        [selectAllBtn setImageEdgeInsets:UIEdgeInsetsMake(0, -10, 0, 0)];
        
        makeSureBtn = [ECUButton buttonWithType:UIButtonTypeCustom];
        [_bottomView addSubview:makeSureBtn];
        [makeSureBtn setTitle:@"取消收藏" forState:0];
        makeSureBtn.backgroundColor = [UIColor colorWithHexString:@"#FF8400"];
        [makeSureBtn setTitleColor:[UIColor whiteColor] forState:0];
        [makeSureBtn addTarget:self action:@selector(makeSureBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view setNeedsUpdateConstraints];
        
        [selectAllBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bottomView.mas_left).offset(15);
            make.centerY.equalTo(_bottomView.mas_centerY);
            make.height.equalTo(_bottomView.mas_height);
            make.width.equalTo(@100);
        }];
        
        [makeSureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_bottomView.mas_centerY);
            make.right.equalTo(_bottomView.mas_right);
            make.height.equalTo(_bottomView.mas_height);
            make.width.equalTo(@(kProportion_Width(650)));
        }];
    }
    return _bottomView;
}

/*
 全选按钮
 */
-(void)selectAllBtnClick:(ECUButton *)btn{
    //循环获取数据源中的每一个item
    if (!btn.selected) {
        btn.selected = YES;
        [btn setTitle:@"取消全选" forState:0];
        [btn setImage:[UIImage imageNamed:@"Mine_circleImage_select"] forState:0];
        
        for (int i = 0; i < self.dataArray.count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionBottom];
            
            //自定义的cell里面布局里面改变编辑状态下,圆圈选中的图片
            NSArray *subviews = [[self.tableView cellForRowAtIndexPath:indexPath] subviews];
            for (id subCell in subviews) {
                if ([subCell isKindOfClass:[UIControl class]]) {
                    for (UIImageView *circleImage in [subCell subviews]) {
                        circleImage.image = [UIImage imageNamed:@"Mine_circleImage_select"];
                    }
                }
            }
        }
        [self.selectorPatnArray removeAllObjects];//全选之前 进行清空数组
        [self.selectorPatnArray addObjectsFromArray:self.dataArray];
        [makeSureBtn setTitle:[NSString stringWithFormat:@"取消收藏(%ld)",self.selectorPatnArray.count] forState:0];
        
    }else{
        btn.selected = NO;
        [btn setTitle:@"全选" forState:0];
        [btn setImage:[UIImage imageNamed:@"Mine_circleImage_normal"] forState:0];
        
        for (int i = 0; i < self.dataArray.count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            [self tableView:self.tableView didDeselectRowAtIndexPath:indexPath];
            [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
            
            [self.selectorPatnArray removeObject:self.dataArray[indexPath.row]];
        }
        
        [makeSureBtn setTitle:[NSString stringWithFormat:@"取消收藏(%ld)",self.selectorPatnArray.count] forState:0];
        
        [self.tableView reloadData];
    }
}

/*
 全部删除操作
 */
-(void)makeSureBtnClick{
    idsArray = [[NSMutableArray alloc]init];
    for (ECMineFavMode *model in self.selectorPatnArray) {//获取取消收藏数组中的id
        [idsArray addObject:model.ID];
    }
    //999 为全选删除的标记 (由于当时封装提示框时,考虑不周全,导致全选此问题)
    isMoreDel = 999;
    [self.tipCustomView showTipviewWithTpe:tipTypeOfCancelFavorite andIndexPath:isMoreDel];
}

#pragma mark ECTipCustomViewDelegate
-(void)tipCustomViewOfSureBtnClickWithRow:(NSInteger)row{
    //执行删除操作
    if (row == 999) {//全选删除操作
        DLog(@"全选删除---%@-----行",idsArray);
        [self cancelFavOfMyCourseWith:idsArray];
    }else{//单独删除操作
        DLog(@"侧滑删除---%ld-----行",row);
        ECMineFavMode *model = self.dataArray[row];
        [self cancelFavOfMyCourseWith:@[model.ID]];
    }
}

/*
 取消收藏请求
 */
-(void)cancelFavOfMyCourseWith:(NSArray *)idsArray{
    
    NSString *idsStr = [idsArray componentsJoinedByString:@","];
    DLog(@"%@",[[UserInfoManager shareUser] token]);
    [HWHttpTool requestWithMethod:@"POST"
                              url:URL_POST_CancelFavroite
                           params:@{@"ids":idsStr
                                    }
                          headers:@{@"X-AUTH-TOKEN":[[UserInfoManager shareUser] token]}
                          success:^(id json) {

                              for (int i = 0; i < idsArray.count; i++) {//根据idsArray的id来进行删除
                                  NSString *id_ID = idsArray[i];
                                  for (int j = 0; j < self.dataArray.count; j++) {
                                      ECMineFavMode *model = self.dataArray[j];
                                      if ([id_ID isEqualToString:model.ID]) {
                                          [self.dataArray removeObjectAtIndex:j];//移除数据源中对应的数据
                                      }
                                  }
                              }
                              
                              if (isMoreDel == 999) {
                                  [self selectMore:nil];
                                  isMoreDel = 0;
                              }
                              
                              if (self.dataArray.count == 0) {//隐藏编辑按钮
                                  self.navigationItem.rightBarButtonItem = nil;
                              }
                              [self.tableView reloadData];//刷新列表
                              [MBProgressHUD showTipMessageInWindow:@"取消收藏成功"];
                          }failure:^(NSError *error) {
                              NSString *str = [ECData_Json requestErrorTipWith:error];
                              DLog(@"%@",str);
                              if (!([str isEqualToString:@"101"] || [str isEqualToString:@"401"])) {
                                  [MBProgressHUD showTipMessageInWindow:kAlertTipOfInternetFailure];
                              }
                          }];
}

/*  懒加载tableview  */
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kNavHeight, kScreenWidth, kScreenHeight-kNavHeight-kSafeAreaBottomHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.emptyDataSetSource = self;
        _tableView.emptyDataSetDelegate = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                     [self getDataWithURL];
        }];
    }
    return _tableView;
}

/*  懒加载数据  */
-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}

- (NSMutableArray *)selectorPatnArray{
    if (!_selectorPatnArray) {
        _selectorPatnArray = [NSMutableArray array];
    }
    return _selectorPatnArray;
}

/**
 进入编辑状态 tableview更新约束 页面添加下部view;
 */
-(void)updateTableviewFram{
    //进入编辑状态 tableview更新约束 页面添加下部view;
    WeakSelf(weakSelf);
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(kNavHeight);
        make.left.equalTo(weakSelf.view.mas_left);
        make.width.equalTo(weakSelf.view.mas_width);
        make.bottom.equalTo(weakSelf.view.mas_bottom).offset(-kProportion_Height(Bottom_Height));
    }];
    
    ///添加底部view
    [self.view addSubview:self.bottomView];
    
    //改变全选按钮的状态
    selectAllBtn.selected = NO;
    [selectAllBtn setTitle:@"全选" forState:0];
    [selectAllBtn setImage:[UIImage imageNamed:@"Mine_circleImage_normal"] forState:0];
    
    [makeSureBtn setTitle:@"取消收藏" forState:0];
}

/**
 退出编辑状态 tableview更新约束 去除页面下部view;
 */
-(void)resetTableviewFram{
    //退出编辑状态 tableview更新约束 去除页面下部view;
    WeakSelf(weakSelf);
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_top).offset(kNavHeight);
        make.left.equalTo(weakSelf.view.mas_left);
        make.width.equalTo(weakSelf.view.mas_width);
        make.bottom.equalTo(weakSelf.view.mas_bottom);
    }];
    ///移除底部view
    [self.bottomView removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
